<template>
  <div class="container">
    <!-- <el-table
      :data="employeesList.rows"
      style="width: 100%;margin-bottom: 20px;"
      row-key="id"
      border
      default-expand-all
      >
      <el-table-column
        width="50"
        align="center"
        prop="index"
        label="序号"
      />
      <el-table-column
        prop="username"
        label="姓名"
        sortable
        width="100">
      </el-table-column>
      <el-table-column
        width="80"
        label="头像"
        align="center"
      >
        <template>
          <div class="avatar">
            <img src="https://img1.baidu.com/it/u=1966616150,2146512490&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1659978000&t=497df6c740d541c5345d3698b35b0df0">
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="mobile"
        label="手机号"
        sortable
        width="100">
      </el-table-column>
      <el-table-column
        prop="workNumber"
        label="工号"
        sortable
        width="90">
      </el-table-column>
      <el-table-column
        prop="formOfEmployment"
        label="聘用形式"
        sortable
        width="110">
      </el-table-column>
      <el-table-column
        prop="departmentName"
        label="部门"
        sortable
        width="80">
      </el-table-column>
      <el-table-column
        prop="correctionTime"
        label="入职时间"
        sortable
        width="110">
      </el-table-column>
      <el-table-column
        prop="name"
        label="状态"
        sortable
        width="90"
      >
        <el-switch
          v-model="value"
          active-color="#13ce66"
          inactive-color="#ff4949">
        </el-switch>
      </el-table-column>
      <el-table-column
        prop="name"
        fixed="right"
        label="操作"
        sortable
        width="300"
      >
        <template slot-scope="scope">
          <el-button type="text" size="small">查看</el-button>
          <el-button type="text" size="small">转正</el-button>
          <el-button type="text" size="small">调岗</el-button>
          <el-button type="text" size="small">离职</el-button>
          <el-button type="text" size="small">角色</el-button>
          <el-button type="text" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table> -->

    <!-- 新增 -->
    <div class="derive">
      <div>
        <el-button type="primary" icon="el-icon-edit">记录</el-button>
      </div>
      <div>
        <el-button type="danger">普通excel导出</el-button>
        <el-button type="info">复杂表头excel导出</el-button>
        <el-button type="success">excel导入</el-button>
        <el-button
          type="primary"
          @click="onAddEmployee"
        >
          新增员工
        </el-button>
      </div>
    </div>
        <!-- 新增员工弹窗 -->
    <el-dialog
      title="新增员工"
      :visible.sync="addEmployeeVisible"
      width="600px"
      @close="onAddEmployeeClose"
      class="add-employee"
    >

      <el-form
        :model="addEmployee"
        status-icon
        :rules="addEmployeeRules"
        ref="addEmployeeForm"
        label-width="100px"
      >

        <el-form-item
          label="姓名"
          prop="username"
        >
          <el-input
            type="text"
            v-model="addEmployee.username"
            autocomplete="off"
          />
        </el-form-item>

        <el-form-item
          label="手机号"
          prop="mobile"
        >
          <el-input
            type="text"
            v-model="addEmployee.mobile"
            autocomplete="off"
          />
        </el-form-item>

        <el-form-item
          label="入职时间"
          prop="timeOfEntry"
        >
          <el-date-picker
            v-model="addEmployee.timeOfEntry"
            type="date"
            placeholder="选择日期"
            format="yyyy-MM-dd"
          />
        </el-form-item>

        <el-form-item
          label="聘用形式"
          prop="formOfEmployment"
        >
          <el-select
            v-model="addEmployee.formOfEmployment"
            placeholder="请选择聘用形式"
          >
            <el-option
              key="1"
              value="1"
              label="正式"
            />
            <el-option
              key="2"
              value="2"
              label="非正式"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          label="工号"
          prop="workNumber"
        >
          <el-input
            type="text"
            v-model="addEmployee.workNumber"
            autocomplete="off"
          />
        </el-form-item>

        <el-form-item
          label="部门"
          prop="departmentName"
        >
          <el-input
            type="text"
            :value="addEmployee.departmentName"
            autocomplete="off"
            @focus="onDepartment"
          />
          <el-tree
            v-show="tree"
            :data="amendDepartment"
            :props="defaultProps"
            @node-click="onDepartmentTreeNodeClick"
            default-expand-all
          />
        </el-form-item>

        <el-form-item
          label="转正时间"
          prop="correctionTime"
        >
          <el-date-picker
            v-model="addEmployee.correctionTime"
            type="date"
            placeholder="选择日期"
            format="yyyy-MM-dd"
          />
        </el-form-item>

      </el-form>

      <footer>
        <el-button type="primary" @click="onAddEmployeeOk">确定</el-button>
        <el-button>取消</el-button>
      </footer>

    </el-dialog>
    <!-- <el-dialog
      title="分配角色"
      :visible.sync="addEmployeeVisible"
      width="400px"
      @close="onRoleDetailClose"
    >
      <el-form
        ref="addEmployeeform"
        :model="addEmployee"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item
          label="姓名"
          prop="username"
        >
          <el-input
            v-model="addEmployee.username"
            placeholder="请输入名字"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item
          label="手机号"
          prop="mobile"
        >
          <el-input
            v-model="addEmployee.mobile"
            placeholder="请输入手机号"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item
          label="入职时间"
          prop="timeOfEntry"
        >
          <el-date-picker
            v-model="addEmployee.timeOfEntry"
            type="date"
            placeholder="请选择入职日期"
          />
        </el-form-item>
        <el-form-item
          label="聘用形式"
          prop="formOfEmployment"
        >
          <el-select
            v-model="addEmployee.formOfEmployment"
            placeholder="请选择聘用形式"
          >
            <el-option
              label="正式"
              :value="1"
            />
            <el-option
              label="非正式"
              :value="2"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="工号"
          prop="workNumber"
        >
          <el-input
            v-model="addEmployee.workNumber"
            placeholder="请输入工号"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item
          label="部门"
          prop="departmentName"
        >
          <el-input
            :value="addEmployee.departmentName"
            placeholder="请选择部门"
            autocomplete="off"
            @focus="onDepartment"
          />
        </el-form-item>
        <el-tree
          v-show="tree"
          :data="amendDepartment"
          :props="defaultProps"
          @node-click="onNodeClick"
          default-expand-all
        />
        <el-form-item
          label="转正时间"
          prop="correctionTime"
        >
          <el-date-picker
            v-model="addEmployee.correctionTime"
            type="date"
            placeholder="请选择转正时间"
          />
        </el-form-item>
      </el-form>
        <el-button
          type="primary"
          @click="onConfirm"
          :loading="loadingonConfirm"
        >
          确定
        </el-button>
        <el-button>取消</el-button>
    </el-dialog> -->
    <div class="derive-list">
      <my-table
        :table-props="{
          data: employeesList.rows,
          border: true
        }"

        :columns="[
          { label: '序号', prop: 'index', width: 80, align: 'center' },
          { label: '姓名', prop: 'username', sortable: true, width: 80, align: 'center' },
          { label: '头像', slotName: 'Photo', align: 'center' },
          { label: '手机号', prop: 'mobile', sortable: true, align: 'center'},
          { label: '工号', prop: 'workNumber', sortable: true, align: 'center'},
          { label: '聘用形式', prop: 'formOfEmployment', sortable: true, align: 'center'},
          { label: '部门', prop: 'departmentName', sortable: true, align: 'center'},
          { label: '入职时间', prop: 'timeOfEntry', sortable: true, align: 'center'},
          { label: '状态', slotName: 'status', align: 'center' },
          { label: '操作', slotName: 'operators', align: 'center', fixed: 'right'},
        ]"
        :pagination-props="{
          layout: 'total, pager',
          total: employeesList.total,
        }"
        :pagination-events="events"
      >
        <template v-slot:Photo="scope">
          <div class="avatar">
            <img :src="scope.row.staffPhoto">
          </div>
        </template>
        <template #status>
          <el-switch :value="true" />
        </template>
        <template
          v-slot:operators="scope"
        >
          <el-button type="text" size="small">查看</el-button>
          <el-button type="text" size="small">转正</el-button>
          <el-button type="text" size="small">调岗</el-button>
          <el-button type="text" size="small">离职</el-button>
          <el-button type="text" size="small" @click="onRowClick(scope.row.id)">角色</el-button>
          <el-button type="text" @click="onDeleteClick(scope.row.id)">删除</el-button>
          <!-- <el-button @click="onDeleteClick(scope.row.id)" type="text" size="small">删除</el-button> -->
        </template>
      </my-table>
    </div>
    <el-dialog
      title="分配角色"
      :visible.sync="dialogTableVisible"
      width="400px"
      @close="onRoleDetailClose"
    >
      <!-- `checked` 为 true 或 false -->
      <!-- <el-form ref="form" :model="form">
        <el-checkbox-group v-model="form.roleIds">
          <el-checkbox
          v-for="item in roleemployeeList"
          :key="item.id"
          :lable="item.id"
          name="type"
        >
          {{ item.name }}
        </el-checkbox>
      </el-checkbox-group>
      </el-form> -->
      <el-form
        :model="form"
        label-width="80px"
      >
        <el-checkbox-group
          v-model="form.roleIds"
          v-loading="roleLoading"
        >
          <el-checkbox
            v-for="item in roleemployeeList.rows"
            :key="item.id"
            :label="item.id"
            name="type"
          >
            {{ item.name }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form>
      <span>
        <el-button
          type="primary"
          @click="onEnsure"
        >
          确定
        </el-button>
        <el-button>取消</el-button>
      </span>
    </el-dialog>
    <!-- <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="currentPagebtn"
        layout="total, sizes, prev, pager, next"
        :total="employeesList.total">
      </el-pagination>
    </div> -->
  </div>
</template>

<script>
import { mapState, mapActions, mapGetters } from 'vuex'
import * as allotRoleApi from '@/api/allotrole'
import * as postUserApi from '@/api/user'
export default {
  name: 'Employees',
  data() {
    // const num = /^1[3-9]\d{9}$/
    // const validatePass = (rule, value, callback) => {
    //   if (!num.test(value)) {
    //     callback(new Error('请输入正确号码'))
    //   }
    // }
    const validateMobile = (rule, value, callback) => {
      const telReg = /^1[3-9]\d{9}$/
      if (!telReg.test(value)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    }
    const validateNull = (rule, value, callback) => {
      console.log(value);
      if (!value.trim()) {
        callback(new Error(this.$t('值不能为空')))
      } else {
        callback()
      }
    }
    const validateDate = (rule, value, callback) => {
      if (!value) {
        callback(new Error(this.$t('时间不能为空')))
      } else {
        callback()
      }
    }
    return {
      currentPage: 1,
      value: true,
      currentPagebtn: 10,
      events: {
        'current-change': this.handleCurrentChange
      },
      dialogTableVisible: false,
      form: {
        roleIds: []
      },
      roleLoading: false,
      addEmployeeVisible: false,
      addEmployee: {
        username: '嘿嘿',
        mobile: '13599999999',
        formOfEmployment: '1',
        workNumber: '16412',
        departmentName: '人事部',
        timeOfEntry: '2022-03-01',
        correctionTime: '2022-03-01'
      },
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      // rules: {
      //   username: [
      //     { required: true, message: '请输入姓名', trigger: 'blur' },
      //     { min: 2, max: 4, message: '姓名为2-4位', trigger: 'blur' }
      //   ],
      //   mobile: [
      //     { required: true, message: '请输入手机号', trigger: 'blur' },
      //     { validator: validatePass, trigger: 'blur' }
      //   ],
      //   timeOfEntry: [
      //     { required: true, message: '请选择入职时间', trigger: 'blur' }
      //   ],
      //   formOfEmployment: [
      //     { required: true, message: '', trigger: 'blur' }
      //   ],
      //   workNumber: [
      //     { required: true, message: '请输入工号', trigger: 'blur' }
      //   ],
      //   departmentName: [
      //     { required: true, message: '请选择部门', trigger: 'blur' }
      //   ],
      //   correctionTime: [
      //     { required: true, message: '请选择转正时间', trigger: 'blur' }
      //   ],
      // },
            // 新增员工校验规则
      addEmployeeRules: {
        username: [{ required: true, trigger: 'blur', validator: validateNull }],
        mobile: [{ required: true, trigger: 'blur', validator: validateMobile }],
        timeOfEntry: [{ required: true, trigger: 'blur', validator: validateDate }],
        formOfEmployment: [{ required: true, trigger: 'blur', validator: validateNull }],
        workNumber: [{ required: true, trigger: 'blur', validator: validateNull }],
        departmentName: [{ required: true, validator: validateNull }],
        correctionTime: [{ required: true, trigger: 'blur', validator: validateDate }]
      },
      tree: false,
      loadingonConfirm: false
    }
  },
  //   watch: {
  //     form: {
  //     deep:true,
  //     handler(newValue) {
  //       console.log(newValue);
  //     }
  //   }
  // },
  created() {
    this.updateGetEmployeesList({
      page: this.currentPage,
      size: this.currentPagebtn
    }),
    this.updateDepartmentList()
    this.updateroleemployeeList({
      page: 1,
      pagesize: 100
    })
  },
  computed: {
    ...mapState('employees', [
      'employeesList'
    ]),
    ...mapGetters('department', [
      'amendDepartment'
    ]),
    ...mapState('staffinformation', [
      'staffinformationList'
    ]),
    ...mapState('roleemployee', [
      'roleemployeeList'
    ]),
    ...mapState('department', [
      'departmentList'
    ])
  },
  methods: {
    ...mapActions('employees', [
      'updateGetEmployeesList'
    ]),
    ...mapActions('staffinformation', [
      'updategetstaffinformationList'
    ]),
    ...mapActions('roleemployee', [
      'updateroleemployeeList'
    ]),
    ...mapActions('department', [
      'updateDepartmentList'
    ]),
    // 新增员工弹出框
    onAddEmployee() {
      this.addEmployeeVisible = true
    },
    // 新增员工确认
    onAddEmployeeOk() {
      //  postUserApi.postUser(this.addEmployee)
      this.$refs.addEmployeeForm.validate(async (valid) => {
        if (valid) {
          await postUserApi.postUser(this.addEmployee)
            .then(msg => this.$message.success(msg))
            .catch(msg => this.$message.error(msg))

          // 请求完成后关闭窗口
          this.onAddEmployeeClose()
          // // 请求完成后刷新列表
          // this.updateEmployeeList({
          //   page: this.currentPage,
          //   size: this.pageSize
          // })
        } else {
          this.$message.error('请输入正确的表单信息');
          return false;
        }
      })

      // this.loadingonConfirm = true;
      // await postUserApi.postUser(this.addEmployee);
      // this.loadingonConfirm = false;
      // this.tree = false
    },
    // 删除员工
    onDeleteClick(id) {
      console.log(id)
       this.$confirm('确定删除该用户？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await postUserApi.deleteUser(id)
            .then(msg => this.$message.success(msg))

        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })

      // postUserApi.deleteUser(id)
    },
    // 分配部门
    onDepartment() {
      // this.updateDepartmentList()
      this.tree = true
    },
    // 分配角色确认
    async onEnsure() {
      await allotRoleApi.allotRole({
        id: this.staffinformationList.id,
        roleIds: this.form.roleIds
      }),
      this.dialogTableVisible = false
    },
    // 部门树型结构
    onDepartmentTreeNodeClick(data) {
      this.addEmployee.departmentName = data.name
    },
    //  handleSizeChange(val) {
    //   this.currentPage = 1;
    //   this.currentPagebtn = val
    //   this.updateGetEmployeesList({
    //     page: this.currentPage,
    //     size: this.currentPagebtn
    //   })
    // },
    onRoleDetailClose() {
      this.form.roleIds = []
    },
    // 关闭新增员工窗口
    onAddEmployeeClose() {
      this.addEmployeeVisible = false
      this.tree = false
      this.onAddEmployeeReset()
    },
    onAddEmployeeReset() {
      this.$refs.addEmployeeForm.resetFields()
      this.tree = false
    },
    handleCurrentChange(val) {
      this.currentPage = val

      this.updateGetEmployeesList({
        page: this.currentPage,
        size: this.currentPagebtn
      })
    },
    // 点击角色弹窗
    async onRowClick(val) {
      this.dialogTableVisible = true
      this.roleLoading = true
      await this.updategetstaffinformationList(val)
      this.form.roleIds = this.staffinformationList.roleIds
      this.roleLoading = false

    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/assets/styles/common.scss";

.container {
  padding: 16px;

  @include avatar(20px);
  .avatar {
    display: inline-block;
  }

  .derive,
  .derive-list {
  padding: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
  border-radius: 4px
  }

  .derive {
    display: flex;
    justify-content: space-between;
    margin-bottom: 8px;
  }

  .user-name {
    display: flex;
    align-items: center;
  }
}

::v-deep .el-input--small .el-input__inner {
  width: 150px;
}

</style>
